package com.central.oauth.controller;

import com.central.common.feign.ProjectService;
import com.central.common.feign.RoleService;
import com.central.common.model.*;
import com.central.oauth2.common.util.AuthUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Tindy
 * @date 2021/6/28
 * @describe
 */
@Api(tags = "项目切换")
@Slf4j
@RestController
@RequestMapping("/project")
public class ProjectController {
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private RoleService roleService;


    @ApiOperation(value = "切换项目")
    @GetMapping("/switch")
    public Result switchProjects(HttpServletRequest request, Long proId) {
        try {
            String token = AuthUtils.extractToken(request);
            OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token);
            OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token);
            SysUser user = (SysUser) oAuth2Authentication.getPrincipal();
            user.setCurrentProjectId(proId);
            SysProject project = projectService.findById(proId);
            user.setProName(project.getName());
            List<ProUserRole> proUserRoles = projectService.findRolesByUserId(proId, user.getId());
            if(proUserRoles.size()==0){
                return Result.failed("操作失败：非项目成员");
            }
            Map<String, SysRole> roleMap = roleService.findRoleMap();
            List<SysRole> proRoles=new ArrayList<>();
            for (ProUserRole proUserRole : proUserRoles) {
                proRoles.add(roleMap.get(proUserRole.getRoleId().toString()));
            }
            user.setProRoles(proRoles);
            tokenStore.removeAccessToken(oAuth2AccessToken);
            tokenStore.storeAccessToken(oAuth2AccessToken, oAuth2Authentication);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("switch-project-error", ex);
            return Result.failed("操作失败");
        }
    }
}
